package com.example.growthmuseum.data.model.Repository;

import android.support.annotation.NonNull;

import com.example.growthmuseum.ServiceFactory;
import com.example.growthmuseum.data.model.CallBackListener;
import com.example.growthmuseum.data.model.Goods;
import com.example.growthmuseum.data.model.Result;
import com.example.growthmuseum.service.GoodsService;
import com.orhanobut.logger.Logger;

import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by Jacob on 2016/10/30.
 */
public class GoodsRepository {
    private static GoodsRepository INSTANCE = null;

    private GoodsService goodsService;

    private GoodsRepository() {

        this.goodsService = ServiceFactory
                .createRetrofitService(GoodsService.class,
                        ServiceFactory.BASE_URL);
    }
    public static GoodsRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new GoodsRepository();
        }
        return INSTANCE;
    }

    public void getCompetitionsByUserId(Integer page, Integer rows,
                                        @NonNull
                                        final Integer userId,
                                        @NonNull
                                        final CallBackListener<List<Goods>> callback) {
        checkNotNull(callback);


        goodsService.getGoodsListByUserId(page, rows, userId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<Goods>>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<Goods>> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            callback.onNext(result.getBean());
//                            putInCache("releasedCompetitions" + page + "_" + rows,
//                                    JSON.toJSONString(result.getBean()));
//                            获取十条数据
                        } else {
                            Logger.e(result.getMessage());
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }
}
